package com.ljh.lottery.common.advice;

import com.ljh.lottery.common.utils.JacksonUtil;
import com.ljh.lottery.pojo.response.CommonResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author: Themberfue
 * @date: 2025/4/8 12:27
 * @description:
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String) {
            return JacksonUtil.writeValueAsString(
                    CommonResult.success(body));
        } else if (body instanceof CommonResult<?>) {
            return body;
        }
        return CommonResult.success(body);
    }
}
